package com.GlobalPaint.app.ui;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatDelegate;
import android.text.TextUtils;

import com.GlobalPaint.app.BuildConfig;
import com.GlobalPaint.app.R;
import com.GlobalPaint.app.ui.Login.Login;
import com.GlobalPaint.app.utils.CommUtility;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.SettingsUtil;
import com.baidu.mapapi.SDKInitializer;
import com.lzy.okhttputils.OkHttpUtils;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.utils.Log;

import org.xutils.x;

/**
 * Created by Administrator on 2016/7/13.
 */
public class App extends Application {

    /**
     * 全局上下文，方便使用
     */
    public static Context context;
    public static Handler mHandler;
    public static LocalBroadcastManager localBroadcastManager;
        {

            PlatformConfig.setWeixin("wxef98eaaf123d15e0", "0ede13e57a4d0a392467ac9b67b6988f");
            PlatformConfig.setQQZone("1106179746", "NvqJddvzB2PAnkCO");
            PlatformConfig.setSinaWeibo("3921700954", "04b48b094faeb16683c32669824ebdad", "http://sns.whalecloud.com");
        }

    @Override
    public void onCreate() {
        super.onCreate();
        // 拍照权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        UMShareAPI.get(this);//初始化友盟分享

        mHandler = new Handler();
        context =this;
        if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(SettingsUtil.KEY_NIGHT_MODE, false)) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
        //必须调用初始化
        OkHttpUtils.init(this);

        localBroadcastManager= LocalBroadcastManager.getInstance(context);//注册广播
        PushAgent mPushAgent = PushAgent.getInstance(this);
        // 首先重新设置包名
        mPushAgent.setResourcePackageName(R.class.getPackage().getName());
//注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                String s = deviceToken;
                DataManager.deviceToken = deviceToken;
                android.util.Log.d("devicetoken", s);
            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });
        /**
         * 自定义行为的回调处理
         * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                if(DataManager.userEntity!=null){
                    if(DataManager.userEntity.getCookie()!=null){
                        if(msg.extra!=null){
                            if (msg.extra.get("groupLXID") != null || !TextUtils.isEmpty(msg.extra.get("groupLXID"))) {
                                CommUtility.openActivity(context, msg.extra.get("activity"),msg.extra.get("fkid"),msg.extra.get("groupLXID"));
                            }else {
                                CommUtility.openActivity(context, msg.extra.get("activity"),msg.extra.get("fkid"),"-1");
                            }
                        }
                    }
                }else {
                    Intent intent=new Intent(App.context, Login.class);
                    intent.putExtra("activity",msg.extra.get("activity"));
                    intent.putExtra("fkid",msg.extra.get("fkid"));
                    intent.putExtra("groupLXID",msg.extra.get("groupLXID"));
                    intent.putExtra("app",msg.extra.get("app"));
                    App.context.startActivity(intent);
                }


                //   Toast.makeText(context, msg.extra.get("activity"), Toast.LENGTH_LONG).show();
            }
        };
        //使用自定义的NotificationHandler，来结合友盟统计处理消息通知
        //参考http://bbs.umeng.com/thread-11112-1-1.html
        //CustomNotification Handler notificationClickHandler = new CustomNotificationHandler();
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        //以下都不是必须的，根据需要自行选择
        OkHttpUtils.getInstance()//
                .debug("OkHttpUtils")                                              //是否打开调试
                .setConnectTimeout(OkHttpUtils.DEFAULT_MILLISECONDS)               //全局的连接超时时间
                .setReadTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS)                  //全局的读取超时时间
                .setWriteTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS);                 //全局的写入超时时间
        //.setCookieStore(new MemoryCookieStore())                           //cookie使用内存缓存（app退出后，cookie消失）
        //.setCookieStore(new PersistentCookieStore())                       //cookie持久化存储，如果cookie不过期，则一直有效
               /* .addCommonHeaders(headers)                                         //设置全局公共头
                .addCommonParams(params);                                          //设置全局公共参数*/
        DataManager.context = getApplicationContext();


        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。html5

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);


        // xUtils的初始化
        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG); // 是否输出debug日志, 开启debug会影响性能.
    }
}
